package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.network.ACHMessages;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.function.Supplier;

public class ComponentSpawnS2CPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public ComponentSpawnS2CPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public ComponentSpawnS2CPacket(String ID, int componentId, int rideableId) {
        tag = new CompoundTag();
        tag.putString("ID", ID);
        tag.putInt("componentId", componentId);
        tag.putInt("rideableId", rideableId);
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        String ID = tag.getString("ID");
        int componentId = tag.getInt("componentId");
        int rideableId = tag.getInt("rideableId");
        ACHeli.LOGGER.info("ComponentSpawnS2CPacket => ID: " + ID);
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            if (localPlayer != null) {
                ClientLevel level = localPlayer.clientLevel;
                if  (level.getEntity(rideableId) instanceof RideableEntity rideable
                        && level.getEntity(componentId) instanceof ComponentEntity component
                ) {
                    component.setID(ID);
                    component.setUp(rideable, rideable.factory
                                    .getProductFunction()
                                    .getFL()
                                    .getComponentFLByID(ID));


                    component.setPos(rideable.getX(), rideable.getY(), rideable.getZ());
                    component.startRiding(rideable, true);

                }

            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(ComponentSpawnS2CPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_CLIENT)
                .decoder(ComponentSpawnS2CPacket::new)
                .encoder(ComponentSpawnS2CPacket::toBytes)
                .consumerMainThread(ComponentSpawnS2CPacket::handle)
                .add();
    }
}